package com.heng.futureDemo;

import org.junit.Test;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class AFutureAPIDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {


        FutureTask<String> futureTask = new FutureTask<>(()->{
            System.out.println(Thread.currentThread().getName() + "\t---come in");
            try{TimeUnit.SECONDS.sleep(5);}catch (InterruptedException e) {e.printStackTrace();}
            return "task over";
        });
        Thread t1 = new Thread(futureTask,"t1");
        t1.start();
        System.out.println(Thread.currentThread().getName() + "\t---忙其他任务了");
        while (true) {
            if(futureTask.isDone()) {//轮询
                System.out.println(futureTask.get());
                break;
            }else {
                try {TimeUnit.MILLISECONDS.sleep(500);
                    System.out.println("正在处理中...");
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    public void m2() throws InterruptedException, ExecutionException, TimeoutException {
        FutureTask<String> futureTask = new FutureTask<>(()->{
            System.out.println(Thread.currentThread().getName() + "\t---come in");
            try{TimeUnit.SECONDS.sleep(5);}catch (InterruptedException e) {e.printStackTrace();}
            return "task over";
        });

        Thread t1 = new Thread(futureTask,"t1");
        t1.start();
        System.out.println(Thread.currentThread().getName() + "\t---忙其他任务了");

//        System.out.println(futureTask.get());//阻塞，要等到结果才能离开，容易程序产生阻塞！一般把get放在最后面。
        //如果不想等待，可以自动离开
        System.out.println(futureTask.get(6,TimeUnit.SECONDS));
//        System.out.println("over!!!");
    }
}
